package com.hlkj.pay.controller.common;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.date.LocalDateTimeUtils;
import com.hlkj.pay.app.transfer.MessageRecordDoToResp;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.dto.common.TemplateQueryDto;
import com.hlkj.pay.dto.common.MessageRecordQueryDto;
import com.hlkj.pay.infrastructure.model.common.MessageRecordDO;
import com.hlkj.pay.infrastructure.model.common.TemplateDO;
import com.hlkj.pay.service.common.IMessageRecordService;
import com.hlkj.pay.service.common.ITemplateService;
import com.hlkj.pay.vo.common.req.MessageRecordPageReq;
import com.hlkj.pay.vo.common.resp.MessageRecordResp;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.BeanUtil;

/**
 * Description: 模板基础接口
 *
 * @author monk@techsun.com
 * @date 2023/3/23
 */
@Tag(name = "短信发送记录服务")
@RestController
@RequestMapping("/v1/common/message")
@RequiredArgsConstructor
@Slf4j
public class MessageRecordController  extends BaseController {

    private final IMessageRecordService messageRecordService;
    private final ITemplateService templateService;
    @Operation(summary = "分页查询")
    @GetMapping("/page")
    CommonResult<PageResult<MessageRecordResp>> queryMessageRecordPage(@Validated MessageRecordPageReq pageParam){
        MessageRecordQueryDto messageRecordQueryDto = BeanUtil.copyProperties(pageParam, MessageRecordQueryDto.class);
        if (StringUtils.hasText(pageParam.getStartTime())) {
            try {
                LocalDateTime startTime = LocalDateTimeUtil.parse(pageParam.getStartTime(),
                        DatePattern.NORM_DATE_FORMATTER);
                messageRecordQueryDto.setStartSendTime(LocalDateTimeUtils.datatimeToTimestamp(startTime));
            } catch (Exception e) {
                log.warn("queryMessageRecordPage cover time error:{}", e.getMessage());
            }
        }
        if (StringUtils.hasText(pageParam.getEndTime())) {
            try {
                LocalDateTime endTime = LocalDateTimeUtil.parse(pageParam.getEndTime(),
                        DatePattern.NORM_DATE_FORMATTER);
                //+ 1 day - 1 s
                LocalDateTime localDateTime = endTime.plusDays(1).plusSeconds(-1);
                messageRecordQueryDto.setEndSendTime(LocalDateTimeUtils.datatimeToTimestamp(localDateTime));
            } catch (Exception e) {
                log.warn("queryMessageRecordPage cover time error:{}", e.getMessage());
            }
        }
        PageResult<MessageRecordDO> pageResult = messageRecordService.queryPage(messageRecordQueryDto);
        List<MessageRecordDO> list = pageResult.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(pageResult, Collections.emptyList());
        }
        List<MessageRecordResp> messageRecordResps = MessageRecordDoToResp.INSTANCE.doToRespList(list);
        Set<String> templateCodes = list.stream().map(MessageRecordDO::getTemplateCode).collect(Collectors.toSet());
        TemplateQueryDto templateQueryDto = new TemplateQueryDto();
        templateQueryDto.setTemplateCodes(templateCodes);
        List<TemplateDO> doList = templateService.queryList(templateQueryDto);
        Map<String, TemplateDO> templateMap = doList.stream()
                .collect(Collectors.toMap(TemplateDO::getTemplateCode, Function.identity(), (t1, t2) -> t2));
        messageRecordResps.stream().forEach(messageRecordResp -> {
            TemplateDO templateDO = templateMap.get(messageRecordResp.getTemplateCode());
            if (templateDO != null) {
                messageRecordResp.setTemplateName(templateDO.getTemplateName());
                messageRecordResp.setBusinessType(templateDO.getBusinessType());
            }
            
        });
        return buildPageResult(pageResult, messageRecordResps);
    };
}
